
package com.xiaoma.myaudience.biz.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.tencent.open.HttpStatusException;
import com.tencent.open.NetworkUnavailableException;
import com.tencent.tauth.IRequestListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.WeiboParameters;
import com.weibo.sdk.android.net.HttpManager;
import com.weibo.sdk.android.sso.SsoHandler;
import com.weibo.sdk.android.util.AccessTokenKeeper;
import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.adapter.PersonalMyActivityAdapter;
import com.xiaoma.myaudience.biz.adapter.PersonalMyAlbumAdapter;
import com.xiaoma.myaudience.biz.app.AudienceApplication;
import com.xiaoma.myaudience.biz.model.PostCommentInfo;
import com.xiaoma.myaudience.biz.model.RankingListModel;
import com.xiaoma.myaudience.biz.model.UserAccount;
import com.xiaoma.myaudience.biz.task.CheckUpdateTask;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.LoginTask;
import com.xiaoma.myaudience.biz.task.PersonCenterinfoTask;
import com.xiaoma.myaudience.biz.task.WeiboLoginTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.biz.util.NeteaseAniConfig;
import com.xiaoma.myaudience.biz.util.NeteaseTraslateAni;
import com.xiaoma.myaudience.biz.view.HorizontalListView;
import com.xiaoma.myaudience.biz.view.LoadingImageView;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.PicUtils;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;

/**
 * 用户登陆页面.
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener, AnimationListener{
	
	private Context mContext;
	private AudienceApplication mApp;
	private UserAccount mUserAccount;
	private LoginTask mLoginTask;
	private PersonCenterinfoTask mPostCommentTask;
	
	/**登陆信息*/
	private View mUnloginLayout;
	private Button mLoginBtn;
	private TextView mForgetPassword;
	private TextView mRegister;
	
	/**未登陆信息*/
	private View mLoginLayout;
	private Button mLogoutBtn; 
	private RelativeLayout mLoginsina;
	private RelativeLayout mLoginqq;
	
	private NeteaseTraslateAni mToDownAnimation;
	private NeteaseTraslateAni mToUpAnimation;
	private NeteaseTraslateAni mToAppear;
	private NeteaseTraslateAni mToDisappear;
	private Display mDisplay;
	private boolean isClickLogin;
	
	private boolean mIsRegister;
	private String mUsername;
	private PostCommentInfo mPostCommentInfo;
	private boolean mIsPostComment;
	private boolean mIsNoLoginOnly;
	private ProgressDialog progressDialog;
	private InputMethodManager mInputMethodManage;
	private ProgressDialog mLoginDialog;
	private ProgressDialog mWeiboLoginProsgressDialog;
    private String mSizeStr;
    private Button button;
	private Tencent mTencent;
	private WeiboLoginTask mWeiboLoginTask;
	private String nickname;
	private static final String qqappid ="100511800";
	
    //private static final String TAG = "sinasdk";
    
    /** 显示认证后的信息，如AccessToken */
    private TextView mText;
    
    /** 微博API接口类，提供登陆等功能  */
    private Weibo mWeibo;
    
    /** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;

    /** 注意：SsoHandler 仅当sdk支持sso时有效 */
    private SsoHandler mSsoHandler;
	private CheckUpdateTask mCheckUpdateTask;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.personal_login);
        
        setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitle(R.string.title_user_login);
        setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitleGravity(Gravity.CENTER);
        setNetEaseTitleBarExtra(R.layout.video_detail_extra_layout);
        button =(Button)findViewById(R.id.show_comments_back_original); 
        button.setVisibility(View.VISIBLE);
        button.setText("编辑");
        
        mSizeStr = PicUtils.composeSize((int) this.getResources().getDimension(
                R.dimen.headline_img_width), (int) this.getResources().getDimension(
                R.dimen.headline_img_height));
//        button.setVisibility(visibility)
        button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this, UserInfoDetailActivity.class);
				startActivity(intent);
			}
		});
        
        findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(LoginActivity.this, PersonalCenterActivity.class);
				startActivity(intent);
				LoginActivity.this.finish();
			}
		});
        
        
        mContext = this;
        mDisplay = getWindowManager().getDefaultDisplay();
        mApp = (AudienceApplication) getApplication();
        
        initViewsById();
        setViewClickListener();
        //initLoginOrNoView();
        initAnimation();
        
        //mInputMethodManage = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
        
    }

    @Override
    protected void onResume() {
    	//initLoginOrNoView();
    	
    	if(!CheckIsLogin()){ // 已登陆
    		setRequestedOrientation(ActivityInfo. SCREEN_ORIENTATION_PORTRAIT);
    		initLoginOrNoView();
    	}
    	super.onResume();
    	initLoginOrNoView();
    }
  //检查是否登录
  	public Boolean CheckIsLogin(){
  		// TODO Auto-generated method stub
  		Boolean islogin = PrefHelper.getBoolean(LoginActivity.this,Constant.LOGIN_ISLOGIN, false);
      	if(islogin){
  	        	Logger.e("登录 了mUsername:");
          			//check the expriedate
          			String loginexprie = PrefHelper.getString(this, Constant.LOGIN_EXPIRESDATE, null);
          			if(loginexprie==null) return false;
          			Date expiretime;
  						expiretime = new Date(loginexprie);
  						int c=expiretime.compareTo(new Date());
  						if(c>=0){
  						   //cookie未过期
  							islogin = true;
  						}else{
  							islogin = false;
  						}
      	}
      	return islogin;
  	}
    
	/**登陆状态确认*/
	private void initLoginOrNoView() {
		Boolean b =CheckIsLogin();
		if(b){ // 已登陆
			
//			String nikeName = mApp.getUserAccount();
//			if(nikeName.contains("@"))
//				nikeName = nikeName.substring(0, nikeName.indexOf("@"));
//			
//			TextView text_nikename = (TextView)mLoginLayout.findViewById(R.id.text_personal_name);
//			text_nikename.setText(String.format("%s%s", 
//					getResources().getString(R.string.str_personal_name), nikeName));
			startGetUserInfoDetailTask();
			showLoinViewStatus(View.VISIBLE, View.GONE);
			startGetUserInfoDetailTask();
			 setNetEaseTitle("个人中心");
		}else{ // 未登陆
			EditText edit_account = (EditText)mUnloginLayout.findViewById(R.id.edit_personal_account);
			if(mIsRegister)
				edit_account.setText(mUsername);
			else
				edit_account.setText("");
			
	    	edit_account.setFocusable(true);
	    	
	    	EditText edit_password = (EditText)mUnloginLayout.findViewById(R.id.edit_personal_password);
	    	edit_password.setText("");
	    	
			showLoinViewStatus(View.GONE, View.VISIBLE);
			
			if (mInputMethodManage != null) {
	        	mInputMethodManage.showSoftInput(edit_account, 0);
	        }
			
		}
		
	}
	
	/**
	 * 登陆组件显示控制
	 * @param logined 登陆组件
	 * @param unlogin 未登陆组件
	 */
	private void showLoinViewStatus(int logined, int unlogin){
		mLoginLayout.setVisibility(logined);
		button.setVisibility(logined);
		setNetEaseTitle(R.string.title_personal_center);
		mUnloginLayout.setVisibility(unlogin);
	}

	/**初始化组件*/
	private void initViewsById() {
		// TODO Auto-generated method stub
		
		mUnloginLayout = findViewById(R.id.rel_unlogin_layout);
		mLoginBtn = (Button)findViewById(R.id.btn_personal_login_submit);
		mForgetPassword = (TextView)findViewById(R.id.text_forget_password);
		mRegister = (TextView)findViewById(R.id.btn_personal_register);
		mLoginsina =(RelativeLayout)findViewById(R.id.rel_personal_sinalogin);
		mLoginqq =(RelativeLayout)findViewById(R.id.rel_personal_qqlogin);
		
		mLoginLayout = findViewById(R.id.lin_logined_layout);
		//mLogoutBtn = (Button)findViewById(R.id.btn_personal_logout); 
		
		//我的所有活动
		findViewById(R.id.myactivity).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(LoginActivity.this, MyPartActivity.class);
				startActivity(intent);
			}
		});
		//我的评论
		findViewById(R.id.new_title).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(LoginActivity.this, ReviewActivity.class);
				intent.putExtra(RankingListModel.PARAM_TYPE, "2");
				intent.putExtra(RankingListModel.PARAM_EVENTID, "0");
				intent.putExtra(ReviewActivity.FROM_ACTIVITY, "LoginActivity");
				startActivity(intent);
			}
		});
		
	}
	
	/**
	 * 设置监听事件
	 */
	private void setViewClickListener() {
		// TODO Auto-generated method stub
		mLoginBtn.setOnClickListener(this);
		//mLogoutBtn.setOnClickListener(this);
		mForgetPassword.setOnClickListener(this);
		mRegister.setOnClickListener(this);
		//sina and qq login
		mLoginqq.setOnClickListener(this);
		mLoginsina.setOnClickListener(this);
	}
	
	/**
	 * 初始话动画
	 */
	private void initAnimation(){
		
		/**向下移动，消失画面*/
		mToDownAnimation = new NeteaseTraslateAni(0, 0, 0, mDisplay.getHeight(), 1, 0);
		mToDownAnimation.setDuration(NeteaseAniConfig.TRASLATE_ANIMATION_DURATION);
		mToDownAnimation.setAnimationListener(this);
		/**向上移动，出现画面*/
		mToUpAnimation = new NeteaseTraslateAni(0, 0, mDisplay.getHeight(), 0, 0, 1);
		mToUpAnimation.setDuration(NeteaseAniConfig.ALPHA_ANIMATION_DURATION);
		mToUpAnimation.setAnimationListener(this);
		/**出现*/
		mToAppear = new NeteaseTraslateAni(0, 0, 0, 0, 0, 1);
		mToAppear.setDuration(NeteaseAniConfig.TRASLATE_ANIMATION_DURATION);
		mToAppear.setAnimationListener(this);
		/**消失*/
		mToDisappear = new NeteaseTraslateAni(0, 0, 0, 0, 1, 0);
		mToDisappear.setDuration(NeteaseAniConfig.ALPHA_ANIMATION_DURATION);
		mToDisappear.setAnimationListener(this);
		
	};
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch (v.getId()) {
		/**登陆*/
		case R.id.btn_personal_login_submit:
			login();
			break;
		/**忘记密码*/
		case R.id.text_forget_password:
			forgetPassword();
			break;
			
		/**注册网易通行证*/
		case R.id.btn_personal_register:
			register();
			break;
		
		/**qq login*/
		case R.id.rel_personal_qqlogin:
			qqlogininit();
			onQQLogin();
			break;
		case R.id.rel_personal_sinalogin:
			initWeibo();
			//mWeibo.anthorize(LoginActivity.this, new AuthDialogListener());
			mSsoHandler = new SsoHandler(this, mWeibo);
            mSsoHandler.authorize(new AuthDialogListener(), null);
			break;
		default:
			break;
		}
		
	}

	
	
	
/**
*Begin:QQ接入代码相关
*/
	@Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(mTencent!=null){
			mTencent.onActivityResult(requestCode, resultCode, data);
		}
	       // SSO 授权回调
	        // 重要：发起 SSO 登陆的Activity必须重写onActivityResult
	        if (mSsoHandler != null) {
	            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
	        }
	 }
	
	private void qqlogininit(){
		 if(mTencent==null){
	        	mTencent = Tencent.createInstance(Constant.QQ_APPID, this.getApplicationContext());
	        }
	}
	
	public void getQQUserInfo()
    {
        mTencent.requestAsync("user/get_simple_userinfo", null,
               "GET", new BaseApiListener("get_simple_userinfo", false), null);
    }
    //qq获取详情接口实现类
	private class BaseApiListener implements IRequestListener {
        private String mScope = "all";
        private Boolean mNeedReAuth = false;

        public BaseApiListener(String scope, boolean needReAuth) {
            mScope = scope;
            mNeedReAuth = needReAuth;
        }

        @Override
        public void onComplete(final JSONObject response, Object state) {
            //showResult("IRequestListener.onComplete:", response.toString());
            doComplete(response, state);
        }

        protected void doComplete(JSONObject response, Object state) {
            try {
                int ret = response.getInt("ret");
                String nickname = response.getString("nickname");
                if (ret == 100030) {
                    if (mNeedReAuth) {
                        Runnable r = new Runnable() {
                            public void run() {
                                mTencent.reAuth(LoginActivity.this, mScope, new QQBaseUiListener());
                            }
                        };
                        
                        LoginActivity.this.runOnUiThread(r);
                    }
                }
                //save into pre
                Looper.prepare();
                PrefHelper.putString(LoginActivity.this,"nickname",nickname);
                if(null != progressDialog)
    				progressDialog.dismiss();
               LoginActivity.this.startWeiboLoginTask("1");
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("toddtest", response.toString());
            }
            
        }

        @Override
        public void onIOException(final IOException e, Object state) {
         	Tips("IRequestListener.onIOException:"+e.getMessage());
        }

        @Override
        public void onMalformedURLException(final MalformedURLException e,
                Object state) {
        	Tips("IRequestListener.onMalformedURLException:"+e.toString());
        }

        @Override
        public void onJSONException(final JSONException e, Object state) {
        	Tips("IRequestListener.onJSONException:"+e.getMessage());
        }

        @Override
        public void onConnectTimeoutException(ConnectTimeoutException arg0,
                Object arg1) {
        	Tips("IRequestListener.onConnectTimeoutException:"+ arg0.getMessage());

        }

        @Override
        public void onSocketTimeoutException(SocketTimeoutException arg0,
                Object arg1) {
        	Tips("IRequestListener.SocketTimeoutException:"+arg0.getMessage());
        }

        @Override
        public void onUnknowException(Exception arg0, Object arg1) {
        	Tips("IRequestListener.onUnknowException:"+arg0.getMessage());
        }

        @Override
        public void onHttpStatusException(HttpStatusException arg0, Object arg1) {
        	Tips("IRequestListener.HttpStatusException:"+arg0.getMessage());
        }

        @Override
        public void onNetworkUnavailableException(NetworkUnavailableException arg0, Object arg1) {
        	Tips("IRequestListener.onNetworkUnavailableException:"+ arg0.getMessage());
        }
    }

	//qq登录
	private void onQQLogin() {
		if(null == mWeiboLoginProsgressDialog){
			mWeiboLoginProsgressDialog = new ProgressDialog(mContext);
			mWeiboLoginProsgressDialog.setMessage("QQ授权中，请稍后");
			mWeiboLoginProsgressDialog.setCancelable(true);
			mWeiboLoginProsgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					//cancelLoginTask();
				}
			});
		}
		mWeiboLoginProsgressDialog.show();
		
        if (!mTencent.isSessionValid()) {
            IUiListener listener = new QQBaseUiListener() {
                protected void doComplete(JSONObject values) {
                }
            };
            mTencent.login(LoginActivity.this, "all", listener);
        } else {
            mTencent.logout(LoginActivity.this);
           // updateLoginButton();
        }
    }
	
	//QQ接入登录实现类
    private class QQBaseUiListener implements IUiListener {

        @Override
	        public void onComplete(JSONObject response) {
        		try {
        			//showLoinViewStatus(View.VISIBLE, View.GONE);
        			//setNetEaseTitle("个人中心");
					String openid = response.getString("openid");
					PrefHelper.putString(LoginActivity.this,"openid",openid);
					String token = response.getString("access_token");
					PrefHelper.putString(LoginActivity.this,"token",token);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	//Tips(response.toString());
	        	//PrefHelper.putBoolean(LoginActivity.this,"islogin",true);
	        	getQQUserInfo();
	        }
	    @Override
		public void onCancel() {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onError(UiError arg0) {
			// TODO Auto-generated method stub
			
		}
    }

    /**
    *end::QQ接入代码相关
    */
    
    
    /**
    *Begin:Webo接入代码相关
    */
    //初始化Webo对象
    private void initWeibo(){
    	if(mWeibo==null){
    		mWeibo = Weibo.getInstance(Constant.SINA_APPKEY, Constant.WEIBO_REDIRECT_URL, Constant.SCOPE);
    	}
    	// 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息，
        // 第一次启动本应用，AccessToken 不可用
        mAccessToken = AccessTokenKeeper.readAccessToken(this);
        if (mAccessToken.isSessionValid()) {
            String date = new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss")
                    .format(new java.util.Date(mAccessToken.getExpiresTime()));
            Tips("access_token 仍在有效期内,无需再次登录: \naccess_token:"
                    + mAccessToken.getToken() + "\n有效期：" + date);
          //获取用户名
            String uidString = PrefHelper.getString(mContext, "uid", "");
            //getUserInfo(mAccessToken.getToken(),uidString);
        } else {
        	Tips("使用SSO登录前，请检查手机上是否已经安装新浪微博客户端，"
                    + "目前仅3.0.0及以上微博客户端版本支持SSO；如果未安装，将自动转为Oauth2.0进行认证");
        }
    	
    }
    
    
    /**
     * 微博认证授权回调类。
     * 1. SSO登陆时，需要在{@link #onActivityResult}中调用mSsoHandler.authorizeCallBack后，
     *    该回调才会被执行。
     * 2. 非SSO登陆时，当授权后，就会被执行。
     * 当授权成功后，请保存该access_token、expires_in等信息到SharedPreferences中。
     */
    private class AuthDialogListener implements WeiboAuthListener {
        
        @Override
        public void onComplete(Bundle values) {
            
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            String uidString = values.getString("uid");
            String code = values.getString("code");
            PrefHelper.putString(LoginActivity.this,"token",token);
            PrefHelper.putString(LoginActivity.this,"openid",uidString);
            if(token==null){
            	getTokenByCode(code);
            }else{
	            mAccessToken = new Oauth2AccessToken(token, expires_in);
	            if (mAccessToken.isSessionValid()) {
	                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
	                        .format(new java.util.Date(mAccessToken.getExpiresTime()));
	                Tips("认证成功: \r\n access_token: " + token + "\r\n" + "expires_in: "
	                        + expires_in + "\r\n有效期：" + date);
	                
	                AccessTokenKeeper.keepAccessToken(LoginActivity.this, mAccessToken);
	                Toast.makeText(LoginActivity.this, "认证成功", Toast.LENGTH_SHORT).show();
	                //获取用户名
	                getUserInfo(token,uidString);
	            }
            }
        }

        @Override
        public void onError(WeiboDialogError e) {
            Toast.makeText(getApplicationContext(), 
                    "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(), "Auth cancel", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(getApplicationContext(), 
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    
	public void getTokenByCode(String code) {
		String url = "https://api.weibo.com/oauth2/access_token";
		WeiboParameters weiboParameters = new WeiboParameters();
		weiboParameters.add("client_id", Constant.SINA_APPKEY);
		weiboParameters.add("client_secret", "af9ba8a11eeb54112a7e3b9f102ebefd");
		weiboParameters.add("grant_type", "authorization_code");
		weiboParameters.add("redirect_uri", Constant.WEIBO_REDIRECT_URL);
		weiboParameters.add("code", code);
		try {
			String result = HttpManager.openUrl(url,"POST", weiboParameters, null);
			JSONObject json = new JSONObject(result);
            String token = json.getString("access_token");
            String expires_in = json.getString("expires_in");
            String uidString = json.getString("uid");
            PrefHelper.putString(LoginActivity.this,"token",token);
            PrefHelper.putString(LoginActivity.this,"openid",uidString);
            mAccessToken = new Oauth2AccessToken(token, expires_in);
            if (mAccessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(mAccessToken.getExpiresTime()));
                Tips("认证成功: \r\n access_token: " + token + "\r\n" + "expires_in: "
                        + expires_in + "\r\n有效期：" + date);
                
                AccessTokenKeeper.keepAccessToken(LoginActivity.this, mAccessToken);
                Toast.makeText(LoginActivity.this, "认证成功", Toast.LENGTH_SHORT).show();
                //获取用户名
                getUserInfo(token,uidString);
            }
			startWeiboLoginTask("2");
		} catch (WeiboException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}  
    
    
	public void getUserInfo(String token,String uid) {
		String url = "https://api.weibo.com/2/users/show.json";
		WeiboParameters weiboParameters = new WeiboParameters();
		weiboParameters.add("access_token", token);
		weiboParameters.add("source", Constant.SINA_APPKEY);
		weiboParameters.add("uid", uid);
		try {
			String result = HttpManager.openUrl(url,
					HttpManager.HTTPMETHOD_GET, weiboParameters, null);
			JSONObject obj = new JSONObject(result);
			PrefHelper.putString(LoginActivity.this,"nickname",obj.getString("name"));
			Log.e("weibo login name:",obj.getString("name")+"");
			startWeiboLoginTask("2");
		} catch (WeiboException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
    
    
    /**
    *end:Webo接入代码相关
    */
    
    
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		cancelLoginTask();
	}
	
	/**
	 * 任务开始执行
	 */
	@Override
	public void onPreExecute(int what) {
		// TODO Auto-generated method stub
		super.onPreExecute(what);
		switch (what) {
		case DataAsyncTask.TASK_LOGIN:

			mLoginBtn.setClickable(false);
			if(null == mLoginDialog){
				mLoginDialog = new ProgressDialog(mContext);
				mLoginDialog.setMessage(getResources().getString(R.string.login_wait_tips));
				mLoginDialog.setCancelable(true);
				mLoginDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						cancelLoginTask();
					}
				});
			}
			mLoginDialog.show();
			break;
			
		case DataAsyncTask.TASK_ACTIVITY_PERSONCENTERINF:
				
				if(null == progressDialog){
					progressDialog = new ProgressDialog(mContext);
					progressDialog.setMessage("加载中");
					progressDialog.setCancelable(true);
					progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
						@Override
						public void onCancel(DialogInterface dialog) {
							// TODO Auto-generated method stub
							cancelLoginTask();
						}
					});
				}
			progressDialog.show();
			
			break;
		case DataAsyncTask.TASK_ACTIVITY_WEIBOLOGIN:
			if(null != mWeiboLoginProsgressDialog){
				mWeiboLoginProsgressDialog.dismiss();
			}else{
				mWeiboLoginProsgressDialog = new ProgressDialog(mContext);
				mWeiboLoginProsgressDialog.setMessage("授权成功，正在转向登录页");
				mWeiboLoginProsgressDialog.setCancelable(true);
				mWeiboLoginProsgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						//cancelLoginTask();
					}
				});
			}
			mWeiboLoginProsgressDialog.show();
			break;
		default:
			break;
		}
	}
	
	
	/**
	 * 任务完成
	 */
	@Override
	public void onPostExecute(int what, Object o) {
		// TODO Auto-generated method stub
		super.onPostExecute(what, o);
		Boolean b ;
		switch (what) {
		/**登陆*/
		case DataAsyncTask.TASK_LOGIN:
			if(null != mLoginDialog)
				mLoginDialog.dismiss();
			
			mLoginBtn.setClickable(true);
			if (o == null) {
				// TODO 有加载错误...
				Tips(getResources().getString(R.string.login_error));
				return;
			}else{
				Map<String,Object> m =(Map<String,Object>)o;
				b = (Boolean)m.get("islogin");
				if(!b){
					//Tips("网站没有响应");测试用成功
					Tips(R.string.login_error);
					PrefHelper.putBoolean(this,"islogin",false);
				}else{
					String strdata = (String)m.get("data");
					try {
						JSONObject jsonobj = new JSONObject(strdata);
						String uid = jsonobj.getString("uid");
						PrefHelper.putString(this,"uid",uid);
						//激光推送别名
						JPushInterface.setAlias(getApplicationContext(), uid, new TagAliasCallback() {
							@Override
							public void gotResult(int arg0, String arg1, Set<String> arg2) {
								//Tips("极光推送设置代码："+arg0+","+arg1);
							}
						});
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					PrefHelper.putBoolean(this,"islogin",true);
					//Tips("uchome_app_auth:"+m.get("uchome_app_auth")+";uchome_app_user:"+m.get("uchome_app_user"));
					PrefHelper.putString(this,Constant.LOGIN_EXPIRESDATE,(String)m.get(Constant.LOGIN_EXPIRESDATE));
					PrefHelper.putString(this,Constant.LOGIN_COOKIE1,(String)m.get(Constant.LOGIN_COOKIE1));
					PrefHelper.putString(this,Constant.LOGIN_COOKIE2,(String)m.get(Constant.LOGIN_COOKIE2));
					EditText edit_account = (EditText)mUnloginLayout.findViewById(R.id.edit_personal_account);
					if (null != mInputMethodManage) {
						mInputMethodManage.hideSoftInputFromWindow(edit_account.getWindowToken(), 0);		        	
					}
					
					String account = mUserAccount.mAccount;
					String password = mUserAccount.mPassword;
					
					Logger.e("mIsNoLoginOnly:" + mIsNoLoginOnly + " mIsPostComment:" + mIsPostComment);
					startGetUserInfoDetailTask();
				}
			}

			
			break;
			
		case DataAsyncTask.TASK_ACTIVITY_PERSONCENTERINF:
				if(null != progressDialog)
					progressDialog.dismiss();
				
				//取出用户详细信息
				Map<String, Object>  json = (Map)o;
				if(json!=null &&json.size()>0){
					//Map<String, Object>  data = (Map<String, Object>) json.get("data");
					//Tips(json.toString());
					//JSONObject userinfo = (JSONObject)json.get("userinfo");
					Map<String, Object> userinfo= ModelUtils.getMapValue(json, "userinfo");
					if (userinfo != null) {
						
						TextView tvname = (TextView)findViewById(R.id.user_name);
						tvname.setText((String)userinfo.get("username"));
						TextView tvage = (TextView)findViewById(R.id.user_age);
						tvage.setText("  "+(String)userinfo.get("age"));
						TextView tvnengliang = (TextView)findViewById(R.id.nengliang);
						tvnengliang.setText((String)userinfo.get("credit"));
						TextView tvjingyan = (TextView)findViewById(R.id.jingyan);
						tvjingyan.setText((String)userinfo.get("experience"));
					}
					
					List<Map<String,Object>> li  = ModelUtils.getListMapValue(json, "albumpics");
					if(li != null && li.size()>0){
						
					}
					showLoinViewStatus(View.VISIBLE,View.GONE);
					initData(json);
					//startCheckUpdateTask();
				}else{
					Tips("获取用户信息失败");
				}
			
			break;
		case DataAsyncTask.TASK_ACTIVITY_WEIBOLOGIN:
			if(null != mWeiboLoginProsgressDialog)
				mWeiboLoginProsgressDialog.dismiss();
			Map<String, Object>  weibojson = (Map<String, Object>)o;
			if(weibojson!=null && weibojson.size()>0){
				JSONObject returnjson = (JSONObject) weibojson.get("json");
				String code = null;
				try {
					code = (String) returnjson.get("code");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(code.equals("0")){
					//Map<String, Object> data = (Map<String, Object>)weibojson.get("data");
					
					try {
						JSONObject jsonobj = new JSONObject(returnjson.getString("data"));
						String uid = jsonobj.getString("uid");
						PrefHelper.putString(this,"uid",uid);
						//激光推送别名
						JPushInterface.setAlias(mContext, uid, new TagAliasCallback() {
							@Override
							public void gotResult(int arg0, String arg1, Set<String> arg2) {
								//Tips("极光推送设置代码："+arg0+","+arg1);
							}
						});
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					Tips("第三方登录成功");
					showLoinViewStatus(View.VISIBLE,View.GONE);
					PrefHelper.putBoolean(this,"islogin",true);
					//Tips("uchome_app_auth:"+m.get("uchome_app_auth")+";uchome_app_user:"+m.get("uchome_app_user"));
					PrefHelper.putString(this,Constant.LOGIN_EXPIRESDATE,(String)weibojson.get(Constant.LOGIN_EXPIRESDATE));
					PrefHelper.putString(this,Constant.LOGIN_COOKIE1,(String)weibojson.get(Constant.LOGIN_COOKIE1));
					PrefHelper.putString(this,Constant.LOGIN_COOKIE2,(String)weibojson.get(Constant.LOGIN_COOKIE2));
					//startGetUserInfoDetailTask();
					Intent intent = new Intent(mContext, UserInfoDetailActivity.class);
					startActivity(intent);
					//startCheckUpdateTask();
				}else{
					PrefHelper.putBoolean(this,"islogin",false);
					Tips("第三方登录失败原因:"+code);
				}
			}
			
			break;
			
		case DataAsyncTask.TASK_ACTIVITY_CheckUpdate:
			Map<String, Object>  cjson = (Map<String, Object>)o;
			if(cjson.size()<1){
				return;
			}
			String code = (String) cjson.get("code");
			PackageInfo packInfo = null;
			if(code.equals("0")){
				PrefHelper.putBoolean(this,"ischeckedupdate",true);
				Map<String, Object> data =  ModelUtils.getMapValue(cjson, "data");
				 // 获取packagemanager的实例
		           PackageManager packageManager = getPackageManager();
				try {
					packInfo = packageManager.getPackageInfo(getPackageName(),0);
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		           String version = packInfo.versionName;
		           String serverversion = (String)data.get("version");
		           final String downloudpath =(String)data.get("path");
		           String content =(String)data.get("content");
		           if(!version.equals(serverversion)){
		        	  //Tips("有升级信息");

		        	  new AlertDialog.Builder(mContext)
		        	  				 .setTitle(content+" "+serverversion)
		        	  				 .setMessage("确认要升级吗？")
		        	  				 .setPositiveButton("是", new DialogInterface.OnClickListener() {	
																	@Override
																	public void onClick(DialogInterface dialog, int which) {
																		// TODO Auto-generated method stub
																		PrefHelper.putBoolean(mContext,"isupadte",true);
																		Intent intent = new Intent();        
																		intent.setAction("android.intent.action.VIEW");    
																		Uri content_url = Uri.parse(downloudpath);   
																		intent.setData(content_url);  
																		startActivity(intent);
																	}
															 }
		        	  				 )
		        	  				 .setNegativeButton("否", new DialogInterface.OnClickListener() {	
																	@Override
																	public void onClick(DialogInterface dialog, int which) {
																		// TODO Auto-generated method stub
																		PrefHelper.putBoolean(mContext,"isupadte",false);
																	}
															}
		        	  				 )  
									.show();
		           }else{
		        	   //Tips("No升级信息");
		           }
			}
			break;
		default:
			break;
		}
	}
	
	
	
	/**启动第三方登陆任务*/
	public void startWeiboLoginTask(String type) {
		if (mWeiboLoginTask != null) {
			mWeiboLoginTask.cancel(true, true);
		}
		mWeiboLoginTask = new WeiboLoginTask(mContext,
				DataAsyncTask.TASK_ACTIVITY_WEIBOLOGIN, this);
		
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put("openid",PrefHelper.getString(LoginActivity.this,"openid",""));
		cookie.put("token",PrefHelper.getString(LoginActivity.this,"token",""));
		cookie.put("type",type);
		cookie.put("name", PrefHelper.getString(LoginActivity.this,"nickname",""));
		mWeiboLoginTask.execute(cookie);
	}
	
	
	/**启动登陆任务*/
	private void startLoginTask() {
		cancelLoginTask();
		mLoginTask = new LoginTask(mContext,
				DataAsyncTask.TASK_LOGIN, this);
		mLoginTask.execute(mUserAccount);
	}

	/**关闭登陆任务*/
	private void cancelLoginTask() {
		if (mLoginTask != null) {
			mLoginTask.cancel(true, true);
		}
		mLoginTask = null;
	}
	
	
	//检查更新
	private void startCheckUpdateTask(){
		cancelCheckUpdateTask();
	   if(PrefHelper.getBoolean(mContext, "ischeckedupdate", false)){
		   if(!PrefHelper.getBoolean(mContext, "isupadte", true)){
			   return;
	 	   }
	   }else{
		   mCheckUpdateTask = new CheckUpdateTask(mContext,DataAsyncTask.TASK_ACTIVITY_CheckUpdate, this);
		   mCheckUpdateTask.execute(null);
	   }
	}
	
	
	/**关闭登陆任务*/
	private void cancelCheckUpdateTask() {
		if (mCheckUpdateTask != null) {
			mCheckUpdateTask.cancel(true, true);
		}
		mCheckUpdateTask = null;
	}
	/**获取详情任务*/
	private void startGetUserInfoDetailTask() {
		cancelGetUserInfoDetailTask();
		mPostCommentTask = new PersonCenterinfoTask(mContext,
				DataAsyncTask.TASK_ACTIVITY_PERSONCENTERINF, this);
		//取cookie
				Map<String,String> cookie = new HashMap<String,String>();
					cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(LoginActivity.this,Constant.LOGIN_COOKIE1,""));
					cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(LoginActivity.this,Constant.LOGIN_COOKIE2,""));

		mPostCommentTask.execute(cookie);
	}

	/**关闭跟贴任务*/
	private void cancelGetUserInfoDetailTask() {
		if (mPostCommentTask != null) {
			mPostCommentTask.cancel(true, true);
		}
		mPostCommentTask = null;
	}
	
	/**登陆*/
	private void login(){
		
		isClickLogin = true;
		
		EditText editAccount = (EditText)findViewById(R.id.edit_personal_account);
		String account = String.format("%s",editAccount.getText());
		
		EditText editPwd = (EditText)findViewById(R.id.edit_personal_password);
		String password = String.format("%s",editPwd.getText());
		
		if("".equals(account.trim())){
			Tips(getResources().getString(R.string.str_user_account_is_null),Toast.LENGTH_SHORT);
			return;
		}
		if("".equals(password)){
			Tips(getResources().getString(R.string.str_password_is_null),Toast.LENGTH_SHORT);
			return;
		}
		
		
		mUserAccount = new UserAccount();
		mUserAccount.mAccount = account;
		mUserAccount.mPassword = password;
		
		startLoginTask();
		
	}
	
	/**忘记密码*/
	private void forgetPassword(){
		Intent intent = new Intent(mContext, ForgetPasswordActivity.class);
		
		startActivity(intent);
	}
	
	/**注册网易通行证*/
	private void register(){
		
		Intent intent = new Intent(mContext, RegisterActivity.class);
		
		startActivity(intent);
	}
	

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub
		
		if(isClickLogin){
			mLoginLayout.setVisibility(View.VISIBLE);
	        setNetEaseTitle(R.string.title_personal_center);
			button.setVisibility(View.VISIBLE);
		}else{
			mUnloginLayout.setVisibility(View.VISIBLE);
			setNetEaseTitle(R.string.title_user_login);
			button.setVisibility(View.GONE);
		}
		
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		// TODO Auto-generated method stub
		
		if(mApp.isLogin()){
			mLoginLayout.setVisibility(View.VISIBLE);
			setNetEaseTitle(R.string.title_personal_center);
			button.setVisibility(View.VISIBLE);
			mUnloginLayout.setVisibility(View.GONE);
		}else{
			mLoginLayout.setVisibility(View.GONE);
			button.setVisibility(View.GONE);
			setNetEaseTitle(R.string.title_user_login);
			mUnloginLayout.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub
	}
	
	
	   private void initData(Map<String, Object> objMap) {
	    	List<Map<String, Object>> albumpics = null;
	    	List<Map<String, Object>> activityMaps = null;
	    	List<Map<String, Object>> hotActivityMaps = null;
	    	List<Map<String, Object>> newActivityMaps = null;
	    	if (objMap == null) {
	    		return;
			}
	    	albumpics = ModelUtils.getListMapValue(objMap, "albumpics");
	    	activityMaps =ModelUtils.getListMapValue(objMap, "events");
	    	HorizontalListView albumpicsView = (HorizontalListView) findViewById(R.id.person_recommend_list);
	    	HorizontalListView myactivityView = (HorizontalListView) findViewById(R.id.myactivity_list);
	    	
	    	if(albumpics != null){
	    		PersonalMyAlbumAdapter pMyAlbumAdapter = new PersonalMyAlbumAdapter(this, albumpics);
	    		albumpicsView.setAdapter(pMyAlbumAdapter);
	    	}
	    	if (activityMaps != null) {
	    		PersonalMyActivityAdapter myactivity= new PersonalMyActivityAdapter(this, activityMaps);
	    		myactivityView.setAdapter(myactivity);
			}
	        
	        LoadingImageView img =  (LoadingImageView) findViewById(R.id.img);
	        img.setHeadLoadingDrawable(ModelUtils.getStringValue(objMap, "avatar"), mSizeStr);
	        
	        //PersonalMyAlbumAdapter activityAdapter = new PersonalMyAlbumAdapter(this, headlines);
	        //HorizontalListView listView = (HorizontalListView) findViewById(R.id.person_recommend_list);
	        //listView.setAdapter(activityAdapter);
	        
	   }
}
